﻿
using AdbService;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using XChip_Common;

namespace SerialPortHelperLib
{
    public class SerialSend
    {
        /// <summary>
        /// 是否打印
        /// </summary>
        public static bool isDebug = false;
        //记录是否使用USB设备读写
        public static bool IsUsbOpen = false;

        public static uint i2cmIndex = 0; //i2c打开的设备序号
        public static bool m_open = false;  //i2c设备打开标志
        public static bool IsI2C = false; //是否是i2c模式
        public static ulong Paginationaddress = 0x0000; //i2c分页地址
        public static uint i2cid = 0; //i2cid
        // 使用服务定位器获取ADB服务
        private IAdbCommandService adbService = ServiceLocator.AdbCommandService;
        public enum PortMode
        {
            I2C_PORT = 0,
            SERIAL_PORT = 1,
        };

        public enum BaseRegisterMap : uint
        {
            IR_BASE_ADDR = 0xC2000400,
            SPI_BASE_ADDR = 0x82000000,
            SDRAM_BASE_ADDR = 0xC4000000,
        }

        public enum SPIRegisterMap : uint
        {
            SPI_FUNCTION_SELECT = 0x00000000,
            SPI_CONTROL = 0x00000004,
            SPI_RESERVED = 0x00000008,
            SPI_SHIFT_CONTROL = 0x0000000c,
            SPI_SHIFT_TXD0 = 0x00000010,
            SPI_SHIFT_TXD1 = 0x00000014,
            SPI_SHIFT_TXD2 = 0x00000018,
            SPI_SHIFT_TXD3 = 0x0000001C,
            SPI_SHIFT_RXD0 = 0x00000020,
            SPI_SHIFT_RXD1 = 0x00000024,
            SPI_SHIFT_RXD2 = 0x00000028,
            SPI_SHIFT_RXD3 = 0x0000002C,
            SPI_INT_STATUS = 0x00000030,
            SPI_INT_MASK = 0x00000034,
            SPI_BUSY = 0x00000038
        }

        public delegate void SendEventSerialSendNewClick(string msg);
        public static event SendEventSerialSendNewClick SendSerialSendClick;

        public delegate void SendEventSerialSendNewClick2(string msg);
        public static event SendEventSerialSendNewClick2 SendSerialSendClick2;

        public static void Sendser(string ADDR, string reg_data)
        {
            SendSerialSendClick?.Invoke($"{ADDR} 0x{reg_data}");
        }

        /// <summary>
        /// ADB方式读取寄存器（异步）
        /// </summary>
        public static async Task<long> ReadRegisterAsync(ulong addr, SerialPort sPort, bool isusb = false)
        {
            try
            {
                string addressStr = addr.ToString("X8");

                // 构建ADB读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{addressStr},0,0\"";

                // 使用ADB服务执行命令
                string result = ServiceLocator.AdbCommandService.ExecuteAdbCommand(adbCommand, $"读取寄存器地址 {addressStr}");

                // 等待并获取寄存器值
                var logcatResult =  LogcatDataManager.FindByRegisterAddress(addressStr, "Read", 2000);
                if (logcatResult != null && !string.IsNullOrEmpty(logcatResult.Values))
                {
                    // 尝试解析十六进制值
                    if (long.TryParse(logcatResult.Values, System.Globalization.NumberStyles.HexNumber,
                        System.Globalization.CultureInfo.InvariantCulture, out long value))
                    {
                        Console.WriteLine($"[SerialSend] 读取寄存器地址 {addressStr} = {value:X}");
                        Sendser($"R:0x{addressStr}", value.ToString("X2"));
                        return value;
                    }
                    // 尝试解析十进制值
                    else if (long.TryParse(logcatResult.Values, out long decimalValue))
                    {
                        Console.WriteLine($"[SerialSend] 读取寄存器地址 {addressStr} = {decimalValue} (0x{decimalValue:X})");
                        Sendser($"R:0x{addressStr}", decimalValue.ToString("X2"));
                        return decimalValue;
                    }
                }

                Console.WriteLine($"[SerialSend] 读取寄存器地址 {addressStr} 失败，未获取到值");
                Sendser($"R:0x{addressStr}", "读取失败");
                return -1;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[SerialSend ERROR] 读取寄存器地址 {addr:X} 时发生异常: {ex.Message}");
                Sendser($"R:0x{addr:X8}", $"错误: {ex.Message}");
                return -1;
            }
        }

        /// <summary>
        /// ADB方式读取寄存器（同步版本）
        /// </summary>
        public static long ReadRegister(ulong addr, SerialPort sPort, bool isusb = false)
        {
            try
            {
                return -1;
                //return ReadRegisterAsync(addr, sPort, isusb).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[SerialSend ERROR] 同步读取寄存器地址 {addr:X} 时发生异常: {ex.Message}");
                return -1;
            }
        }

        /// <summary>
        /// ADB方式写入寄存器
        /// </summary>
        public static void WriteRegister(ulong addr, ulong value, SerialPort sPort, bool isusb = false)
        {
            try
            {
                string addressStr = addr.ToString("X8");
                string valueStr = value.ToString("X");

                // 构建ADB写入命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"1,{addressStr},{valueStr},0\"";

                //// 使用ADB服务执行命令
                //ServiceLocator.AdbCommandService.ExecuteAdbCommand(adbCommand, $"写入寄存器地址 {addressStr} = {valueStr}");

                Console.WriteLine($"[SerialSend] 写入寄存器地址 {addressStr} = {valueStr}");
                Sendser($"W:0x{addressStr}", valueStr);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[SerialSend ERROR] 写入寄存器地址 {addr:X} 时发生异常: {ex.Message}");
                Sendser($"W:0x{addr:X8}", $"错误: {ex.Message}");
            }
        }

        /// <summary>
        /// ADB方式写入寄存器（重载版本）
        /// </summary>
        public static void WriteRegister(byte a, ulong addr, ulong value, SerialPort sPort)
        {
            WriteRegister(addr, value, sPort);
        }

        // 以下方法保留原有签名但改为ADB实现
        public static long ReadRegister2(byte a, ulong addr, SerialPort sPort)
        {
            return ReadRegister(addr, sPort);
        }

        // 以下方法不再需要，但保留空实现以保持兼容性
        public static byte ReadRegDataARM_New2(uint ADDR, ref uint DATA, SerialPort sPort, int timeoutMilliseconds = 100)
        {
            // ADB模式不再需要串口通信
            Console.WriteLine($"[SerialSend] ADB模式: 跳过串口读取 {ADDR:X8}");
            DATA = 0;
            return 0;
        }

        public static byte SendRegDataARM_New(uint ADDR, uint DATA, SerialPort sPort)
        {
            // ADB模式不再需要串口通信
            WriteRegister(ADDR, DATA, sPort);
            return 0;
        }

        // 保留其他辅助方法
        private static double DateDiffMs(DateTime DateTime1, DateTime DateTime2)
        {
            double dateDiff = -1;
            TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
            TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();
            dateDiff = ts.TotalMilliseconds;
            return dateDiff;
        }

        /// <summary>
        /// 已重载.计算一个时间与当前本地日期和时间的时间间隔,返回的是时间间隔的日期差的绝对值.
        /// </summary>
        public static double DateDiffMs(DateTime DateTime1)
        {
            return DateDiffMs(DateTime1, DateTime.Now);
        }
    }
}